package com.hyz.appalive;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.widget.Toast;

/**
 * @author AigeStudio
 * @since 2016-05-05
 */
public class DaemoService extends Service {
    private static boolean sPower = true;
    private Handler handler = new Handler();


    @Override
    public void onCreate() {
        super.onCreate();
        useForegroundService();
    }

    /**
     * 使用前台服务保活
     * 1.android 4.3之前直接用空的Notification
     * 2.android 4.3之后,新建一个service，构建一个同样id的notification，再结束它
     */
    private void useForegroundService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            startForeground(250, builder.build());
            startService(new Intent(this, CancelService.class));
        } else {
            startForeground(250, new Notification());
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (sPower) {
                    if (System.currentTimeMillis() >= 123456789000000L) {
                        sPower = false;
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(DaemoService.this, "AigeStudio" +
                                    System.currentTimeMillis(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    SystemClock.sleep(3000);
                }
            }
        }).start();
//        return super.onStartCommand(intent, flags, startId);
        return START_REDELIVER_INTENT;
    }
}